package com.ksj.Service;

import com.ksj.Utils.JdbcTool.JdbcTool;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommonService implements MessageListener {

    private static Logger LOG = LoggerFactory.getLogger(CommonService.class);

    //设备类型表缓存
    private static Map<String,Map<String, Object>>deviceTableCache = new HashMap<>();

    @Override
    public void onMessage(Message message) {
        try {
            String msg = ((TextMessage) message).getText();
            CommonService.handleData(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //处理数据
    public static void handleData(String data) {
        //插入消息到dlkdata表
        Map<String, Object> contaner = new HashMap<String, Object>();
        JSONObject obj = new JSONObject(data);
        retrievalJson(new JSONObject(data), contaner);
        //查询数据所属表和表结构
        //获取数据的phone字段并查询数据库所对应的设备类型
        String phone = obj.getString("PHONE");

        Map<String, Object> result;
        //判断是否存在缓存 不存在缓存再去查询然后添加到缓存 存在则直接取缓存
        if (!deviceTableCache.containsKey(phone)){
            String[] clos = {"ShebeiLeixing", "ShebeiBiao"};
            result = JdbcTool.selectMap(clos, "shebeileixing", "phone = '" + phone + "'");
            if (result.size() == 0) {
                LOG.error(phone + "没有配置所对应的设备类型以及设备表~!");
                return;
            }
            deviceTableCache.put(phone,result);
        }else
            result = deviceTableCache.get(phone);
        insertDataToTable(contaner, result.get("ShebeiBiao").toString());

    }


    //递归map
    public static void retrievalJson(JSONObject obj, Map<String, Object> contaner) {
        for (String key : obj.keySet()) {
            if (obj.get(key).getClass().isAssignableFrom(JSONObject.class)) {
                retrievalJson(obj.getJSONObject(key), contaner);
            } else {
                contaner.put(key, obj.get(key));
            }
        }
    }

    //插入数据到数据库
    public static void insertDataToTable(Map<String, Object> contaner, String tableName) {
        int result = JdbcTool.insert(contaner, tableName);
        if (result > 0) {
            LOG.info("插入数据成功~!");
        }
    }


}
